package com.vehiclesecure.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Arrays;
import java.util.List;

/**
 * 日期时间格式配置类
 * 解决LocalDateTime类型无法解析纯日期字符串的问题
 */
@Configuration
public class DateTimeConfig {

    @Bean
    public ObjectMapper objectMapper() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        JavaTimeModule module = new JavaTimeModule();
        
        // 配置多种日期时间格式的解析器
        List<DateTimeFormatter> formatters = Arrays.asList(
            DateTimeFormatter.ISO_DATE_TIME,  // 标准ISO格式 yyyy-MM-dd'T'HH:mm:ss
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),  // 带空格的格式
            DateTimeFormatter.ofPattern("yyyy-MM-dd"),  // 仅日期格式
            new DateTimeFormatterBuilder()
                .appendPattern("yyyy-MM-dd")
                .parseDefaulting(java.time.temporal.ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(java.time.temporal.ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(java.time.temporal.ChronoField.SECOND_OF_MINUTE, 0)
                .toFormatter()  // 仅日期格式，自动补充时间为00:00:00
        );
        
        // 创建一个自定义的反序列化器，尝试多种格式
        module.addDeserializer(LocalDateTime.class, new MultiFormatLocalDateTimeDeserializer(formatters));
        
        builder.modules(module);
        return builder.build();
    }
    
    /**
     * 支持多种日期时间格式的反序列化器
     */
    private static class MultiFormatLocalDateTimeDeserializer extends LocalDateTimeDeserializer {
        private final List<DateTimeFormatter> formatters;
        
        public MultiFormatLocalDateTimeDeserializer(List<DateTimeFormatter> formatters) {
            super(DateTimeFormatter.ISO_DATE_TIME);
            this.formatters = formatters;
        }
        
        @Override
        public LocalDateTime deserialize(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.databind.DeserializationContext ctxt) throws java.io.IOException {
            String value = p.getText();
            if (value == null || value.trim().isEmpty()) {
                return null;
            }
            
            // 尝试使用多种格式解析
            for (DateTimeFormatter formatter : formatters) {
                try {
                    return LocalDateTime.parse(value, formatter);
                } catch (Exception e) {
                    // 尝试下一种格式
                }
            }
            
            // 如果所有格式都失败，抛出异常
            throw new java.io.IOException("Cannot parse date: " + value);
        }
    }
}